#ifndef _StandardSerializer_h_
#define _StandardSerializer_h_

#include "Serializer.h"
#include "Serializable.h"
#include "Persistor/Persistor.h"
#include "RecordSerializer.h"
#include <string>
#include <map>


using namespace common;

namespace persist
{
class StandardSerializer : public Serializer
{
protected:
	Mode mode;

public:
	class ModePush
	{
		Mode& mode;
		Mode saved;
	public:
		ModePush(Mode& m) : mode(m) {saved = mode;}
		~ModePush(){mode=saved;}
	};


protected:
	
	Mode getMode(){return mode;}
	void setMode(Mode m){mode=m;}
//serializer->serialize(data)
	virtual void serialize(void* data, size_t size)=0;
//brute read/write
	template <class T> void read(T& t){ModePush m(mode); mode = READ; *this << t;}
	template <class T> void write(T& t) {ModePush m(mode); mode = EDIT; *this << t;}

//construct object from or flush object's data members to the storage
	virtual void fill(Persistent* _persistent)=0;
//allocate a chunk of storage for a persistent
	virtual void allocate(Persistent* _persistent) {}
	virtual void deallocate(Persistent* _persistent) {}

//allocate a chunk of storage by identifier and return the given name
	virtual std::string allocate(const Identifier& _id)=0;
	virtual void deallocate(const Identifier& _id) {}

	void setName(const std::string& _name){name=_name;}


public:
	StandardSerializer();
	StandardSerializer(const std::string& _name);
	StandardSerializer(const std::string& _name, Persistor::Mode m = READ);
	virtual ~StandardSerializer();

	virtual bool open(const std::string& fname, Persistor::Mode m = READ)=0;
	virtual void close()=0;
	virtual void clear()=0;
	virtual void commit() {}
	virtual bool isOpen()=0;
	virtual bool isReading(){return (mode==READ);}
	virtual void persist(Persistent*& _persistent);

	virtual void load(Persistent* _persistent) {ModePush m(mode);mode=READ;fill(_persistent);}
	virtual void save(Persistent* _persistent) {ModePush m(mode);mode=EDIT;fill(_persistent);}
};
 	
} //namespace

#endif